// 模拟vue路由守卫

import { useLocation, useNavigate, useRoutes } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux';
import { useEffect, useMemo } from 'react';
import { constantRoutes, asyncRoutes } from "@/pages/index";
import { getInfo } from "@/store/action";
import { generateRoutes } from "@/store/permission";

// 白名单 --- 不需要token就可以访问
const whiteList = ['/login']

function Page() {
    const dispatch = useDispatch()
    const navigator = useNavigate()
    const { pathname } = useLocation()
    const { token, roles, accessRoutes } = useSelector(state => state.user)

    useEffect(() => {
        if (token) {
            dispatch(getInfo())
        } else {
            navigator('/login', { replace: true })
        }
    }, [token])

    useEffect(() => {
        if (roles && roles.length > 0) {
            // roles中有规则，配合路由表和算法，生成当前用户可访问的路由规则
            dispatch(generateRoutes(asyncRoutes, roles))
        }
    }, [roles])

    useEffect(() => {
        if (accessRoutes && accessRoutes.length > 0) {
            navigator('/dashboard', { replace: true })
        }
    }, [accessRoutes])

    useEffect(() => {
        if (!whiteList.includes(pathname) && !token) {
            navigator('/login', { replace: true })
        }
        // 如果登录成功，又访问登录页
        if (token && pathname === '/login') {
            navigator('/', { replace: true })
        }
        if (token && pathname === '/') {
            navigator('/dashboard', { replace: true })
        }
    }, [pathname])

    const routes = useMemo(() => {
        const result = [...constantRoutes]
        result[0].children = accessRoutes
        return result
    }, [accessRoutes])
    // console.log(routes);

    const element = useRoutes(constantRoutes)
    return element
}

export default Page